import { Component, OnInit, Input } from '@angular/core';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { Router } from '@angular/router';
import { AxiosService } from '../../axios.service';
import { ActivatedRoute } from '@angular/router';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';


let timeIndex = 0;
let hour;
let minutes;
let seconds;
@Component({
  selector: 'app-zhijian-child',
  templateUrl: './zhijian-child.component.html',
  styleUrls: ['./zhijian-child.component.scss']
})
export class ZhijianChildComponent implements OnInit {

  isLoading;

  widthConfig = ['50px', '50px', '50px', '250px', '250px', '150px', '100px', '100px', '100px', '150px', '200px', '200px', '200px'];
  scrollConfig = { x: '1850px', y: '700px' };

  today: any = new Date();
  public date = new Date();
  public dateDay = this.date.getDay();
  public milliSeconds = this.date.getMilliseconds();
  public weeks = new Array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
  public week = this.weeks[this.dateDay];
  showInfom; // 是否显示表头之前的信息
  userInfo: any;
  name;
  name_PY;
  job_no;
  department;
  department_abb;
  role;
  fileInfom2;
  imglist;
  password;
  listOfData = []; // 表单数组
  ljmc; // 零件名称
  czhi; // 材质
  tzcc; // 图纸尺寸
  box; // 箱号
  gjsl; // 工件数量
  songjian_shuliang; // 送检数量
  songjian_shijian; // 送检时间
  gzsj_tongji; // 工作时间统计
  jgjg;
  gjjcjg; // 工件检测结果
  pinjian_bzhu; // 品检备注
  boxdata; // 接受品检页面跳转的箱号
  url; // 刷新页面
  newurl; // 刷新页面
  isShow = [];
  btnStop = [];
  btnStart = [];
  time; // 页面的时间
  totalTime; // 数据库中的时间
  recordRowClick = -1;
  value; // 计时时间值
  addRemark1; // 是否显示品鉴备注弹出框
  isOkLoadingRemark;
  id;
  unionorder;
  workerName;//工件名
  checkResult;//工件检测结果
  isLoadingCheckResult;
  NGnum;//
  OKnum;

  fileInfom;//文件信息
  isOkLoadingfileInfom;
  link;
  fileList = [];//文件信息列表
  fileName;//文件名
  uploadData; // 上传数据
  workName;//下载文件

  isFileVisible;//删除文件
  isFileOkLoading;
  designRemark;
  addOtherRemark;//退回备注
  RemarkValue;//备注框的值
  isOkLoadingOthRemark;

  isSendVisible;//送出工件
  isSendOkLoading;
  sendChoose;//送出单选框
  sjsj;
  ishowerer = [];
  sfmtime = "00:00:00"
  sjkg = false;
  kssj;
  jsq;
  min = 0;
  dlyy = [{
    name: "人為漏失", show: false
  }, { name: "人力不足", show: false }, { name: "加工不良", show: false }, { name: "缺料", show: false }, { name: "交期短", show: false }, { name: "需求變更", show: false }
    , { name: "待需求單位提供資料", show: false }, { name: "CNC產能不足", show: false }, { name: "待客戶驗證", show: false }]
  dlyynr;
  dlyysz = [];
  pjsl;
  constructor(
    private storage: LocalStorageService,
    private router: Router,
    public axios: AxiosService,
    public activatedRoute: ActivatedRoute,
  ) { }

  ngOnInit(): void {
    //判断路由
    // this.url = window.location.href;
    // this.newurl = this.url.split("$");
    // if (this.newurl.length <= 3) {
    //   this.url += "$1$2$3$2";
    //   window.location.href = this.url;
    // }
    // 修改头部与左侧高度
    document.getElementsByClassName('ant-layout-header')[0].setAttribute('style', 'line-height:21px;padding:0 20px !important;');
    this.userInfo = this.storage.getStorageData('user');
    console.log('--------------------\n', this.userInfo);
    this.name = this.userInfo.name;
    this.name_PY = this.userInfo.name_PY;
    this.job_no = this.userInfo.job_no;
    this.department = this.userInfo.department;
    this.department_abb = this.userInfo.department_abb;
    this.role = this.userInfo.role;
    this.password = this.userInfo.password;
    // 获取上一页面跳转过来的箱号
    this.activatedRoute.params.subscribe((data) => {
      this.boxdata = data['box'];
      console.log(data['ly']);
      console.log(this.boxdata);
    });
    this.allUnion();
  }

  // 注销返回login
  cancel() {
    this.name = this.userInfo.job_no;
    const data = {};
    data['name'] = this.name;
    this.storage.removeAllStorageData();
    this.router.navigate(['/login', data]);
  }

  // 返回上一页面
  back() {
    history.go(-1);
  }

  // 获取数据
  allUnion() {
    // debugger
    console.log(this.boxdata)
    this.axios.axiosPost('QueryCncData', { 'box': this.boxdata, "status": 3, "flag": 1 })
      .then((data) => {
        if (data['result'] === 'ok') {
          console.log(data)
          this.ishowerer = [];

          let b = data['order'];
          //只显示没有被送出或全部送出的工件
          // this.listOfData = b.filter(res => res['status'] == '3')
          this.listOfData = data["order"]
          console.log(this.listOfData)
          // this.storage.setStorageData('result', this.listOfData);
          for (let i = 0; i < this.listOfData.length; i++) {
            this.ishowerer.push(false)
          }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  //点击行显示计时器
  clickLine(key, item) {
    if (item.songjian_shijian) {
      for (var i = 0; i < this.ishowerer.length; i++) {
        if (this.ishowerer[i] == true && i != key) {
          this.min++;
        }
      }
      if (this.min == 0) {
        this.ishowerer[key] = true;
        this.min = 0;
        if (item.timestamp) {
          this.jsq = setInterval(() => {
            // console.log(new Date().getTime() - item2);
            this.sfmtime = this.timeof(new Date().getTime() - item.timestamp);
          }, 1000);
        } else {
          this.sfmtime = "00:00:00"
        }
      } else {
        this.ishowerer[key] = false;
        this.min = 0;

      }
    } else {
      alert("此工件未添加送檢時間")
    }
    console.log(this.ishowerer)

    // if (this.recordRowClick === -1) {
    //   // debugger
    //   timeIndex = 0;
    //   this.recordRowClick = key;
    //   for (let i = 0; i < this.tempData.length; i++) {
    //     if (i !== key) {
    //       this.isShow[i] = false;
    //     } else {
    //       this.isShow[i] = true;
    //     }
    //   }
    //   this.btnStart[key] = true;
    // }
  }


  //开始计时
  start(item, key) {
    if (this.sjkg == false) {
      this.sjkg = true;
      if (this.sfmtime == "00:00:00") {
        this.axios.axiosPost("UpdateWorkOrder", {
          unionorder: item.union_order,
          workorder: item.ljmc,
          id: item.id,
          timestamp: new Date().getTime()
        }).then((data) => {
          console.log(data);
          this.listOfData[key].timestamp = new Date().getTime();
          this.clickLine(key, item)
        })
      } else {
        alert("已經開始計時了")
      }
    } else {
      alert("已經開始計時，請勿重復操作")
    }
    // console.log(key)
    // this.btnStop[key] = true;
    // this.btnStart[key] = false;
    // console.log('00000000000000 \n', this.btnStart)
    // // this.setTime();
    // // timeIndex = 0;
    // console.log(item.total_time)
    // this.value = setInterval(setTime, 1000);

  }



  //结束计时
  end(item, key) {
    if (item.timestamp || this.sfmtime != "00:00:00") {
      this.kssj = 0;
      clearInterval(this.jsq)
      this.ishowerer[key] = false;
      this.min = -1;
      this.sjkg = false;
      this.axios.axiosPost('AddWorkTime', { 'unionorder': item.union_order, id: item.id, "ljmc": item.ljmc, 'endtime': new Date().getTime(), "stage": 3 })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            clearInterval(this.jsq)
            console.log("真棒");
            this.sfmtime = "00:00:00"
            this.allUnion()
          }
        })
        .catch((err) => {
          console.log(err);
        })
    }


    // this.btnStart[key] = false;
    // this.btnStop[key] = true;
    // // debugger
    // if (item.total_time === '') {
    //   item.total_time = 0;
    //   this.totalTime = item.total_time;
    // } else {
    //   this.totalTime = item.total_time;
    // }
    // console.log(this.totalTime)
    // // debugger
    // console.log(item, document.getElementsByClassName('sp')[0].innerHTML)
    // this.time = document.getElementsByClassName('sp')[0].innerHTML;
    // var hour = this.time.split(':')[0];
    // var min = this.time.split(':')[1];
    // var sec = this.time.split(':')[2];
    // var s;
    // s = Number(hour * 3600) + Number(min * 60) + Number(sec);
    // // var total;
    // // total =  parseInt(this.totalTime) + s;
    // // console.log(total,parseInt(this.totalTime))
    // this.recordRowClick = -1;
    // clearInterval(this.value);
    // this.value = null;

    // console.log('11111111111\n', this.isShow)
  }
  timeof(data) {
    var s;
    var hours: number;
    // hours=parseInt((1000 % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    hours = parseInt((data % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)).toString())
    // parseInt((1000 % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    // console.log(hours)
    var minutes = parseInt(((data % (1000 * 60 * 60)) / (1000 * 60)).toString());
    var seconds = parseInt(((data % (1000 * 60)) / 1000).toString());
    s = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutes < 10 ? ('0' + minutes) : minutes) + ':' + (seconds < 10 ? ('0' + seconds) : seconds);
    // console.log(s)
    return s;
  }

  //结束页面生命周期
  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    clearInterval(this.jsq);

  }
  bzclick(name) {
    console.log(name)
    console.log(this.dlyy)
    this.dlyysz = []
    for (var i = 0; i < this.dlyy.length; i++) {
      if (this.dlyy[i].show == true) {
        this.dlyysz.push(this.dlyy[i].name)
      }
    }
    this.dlyynr = this.dlyysz.join(",")
    console.log(this.dlyynr)
  }
  // 点击设计备注
  addRemark(item) {
    this.addRemark1 = true;
    this.pinjian_bzhu = item.pinjian_bzhu;
    this.id = item.id;
    this.designRemark = item.pinjian_bzhu
    this.unionorder = item.union_order;
    this.ljmc = item.ljmc;
    // if (item.pinjian_bzhu.split(",")) {
    //   this.dlyysz = item.pinjian_bzhu.split(",");
    //   for (var i = 0; i < this.dlyysz.length; i++) {
    //     for (var y = 0; y < this.dlyy.length; y++) {
    //       if (this.dlyysz[i] == this.dlyy[y].name) {
    //         this.dlyy[y].show = true;
    //       }
    //     }
    //   }
    // }
  }
  // 确认添加设计备注
  addRemarkOk() {
    this.isOkLoadingRemark = true;
    this.addRemark1 = false;
    this.isOkLoadingRemark = false;
    this.axios.axiosPost('UpdateCncData', { 'id': this.id, 'pinjian_bzhu': this.designRemark })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          // debugger
          this.axios.axiosPost('UpdateWorkOrder', { 'unionorder': this.unionorder, 'workorder': this.ljmc, id: this.id, 'check_remark': this.designRemark })
            .then((data) => {
              console.log(data)
              if (data['result'] === 'ok') {
              }
            })
          this.allUnion();
          this.CancelAddRemark();
        }
      })

  }

  // 取消添加设计备注
  CancelAddRemark() {
    this.addRemark1 = false;
    // for (var i = 0; i < this.dlyy.length; i++) {
    //   this.dlyy[i].show = false
    // }
  }

  //点击添加检测结果
  addResultNum(data) {
    console.log(data)
    this.id = data.id;
    this.unionorder = data.union_order;
    this.ljmc = data.ljmc;
    this.NGnum = data.gjjcjg.split(',')[0] != 'undefined' && data.gjjcjg.split(',')[0] ? data.gjjcjg.split(',')[0] : 0
    this.OKnum = data.gjjcjg.split(',')[1] != 'undefined' && data.gjjcjg.split(',')[1] ? data.gjjcjg.split(',')[1] : 0
    console.log(data, this.NGnum, this.OKnum)
    this.checkResult = true;
    this.sjsj = data.songjian_shijian;
    this.pjsl = data.gjsl;
    console.log(this.pjsl)
  }

  //取消添加工件检测结果
  CancelAddResult() {
    this.checkResult = false;
  }

  //确认添加检测结果
  addCheckResult() {
    console.log(this.OKnum, this.NGnum, this.pjsl);

    if (this.sjsj && this.sjsj != "") {
      if (this.OKnum <= this.pjsl) {
        this.isLoadingCheckResult = true;
        this.checkResult = false;
        this.isLoadingCheckResult = false;
        this.axios.axiosPost('UpdateCncData', { 'id': this.id, 'gjjcjg': this.NGnum + ',' + this.OKnum })
          .then((data) => {
            console.log(data)
            if (data['result'] === 'ok') {
              let check_status;
              if (this.NGnum && this.NGnum === '0') {
                if (this.pjsl == this.OKnum) {
                  check_status = '1';
                } else {
                  check_status = "0";
                }
              } else if (this.NGnum !== '' && this.NGnum != 0) {
                if (this.pjsl == this.OKnum) {
                  check_status = '1';
                } else {
                  check_status = '2';
                }
              }
              // debugger
              this.axios.axiosPost('UpdateWorkOrder', { 'unionorder': this.unionorder, 'workorder': this.ljmc, id: this.id, 'check_status': check_status })
                .then((data) => {
                  console.log(data)
                  if (data['result'] === 'ok') {
                  }
                })
              this.allUnion();
            }
          })
      } else {
        alert("OK數量大於需求總數")
      }
    } else {
      alert("未填写送检时间")

    }
  }

  //上传附件
  downLoad(data) {
    this.fileInfom = true;
    this.workName = data.union_order;
    this.ljmc = data.ljmc;
    console.log(data)
    this.axios.axiosPost('QueryWorkFiles', { 'unionorder': data.union_order, 'workorder': this.ljmc })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.fileList = data['files'];
        }
      })
  }

  //选择要上传的文件名
  openFile(event: any): void {
    // debugger
    this.fileName = event.target; //获取点击得到的对象
    const reader = new FileReader();
    reader.onload = (() => {
      if (reader.result) {
        this.uploadData = reader.result;
        console.log(reader.result);
      }
    });
    reader.readAsDataURL(this.fileName.files[0]);//将文件转为Base64格式
    console.log("hahahaahahahah\n", reader.result)
  }

  Upload() {
    if (this.uploadData == null)
      return;
    this.isLoading = true;
    this.axios.axiosPost('Upload', {
      'unionorder': this.workName, 'workorder': this.ljmc,
      'filename': this.fileName.files[0]['name'], 'filedata': this.uploadData
    })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.isLoading = false;
          alert("上传成功！")
          this.uploadData = null;
          this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workName, 'workorder': this.ljmc })
            .then((data) => {
              if (data['result'] === 'ok') {
                this.fileList = data['files'];
              }
            })
        } else {
          this.isLoading = false;
          alert(data["description"])
        }
      }).catch(function (err) {
        console.log(err)
      })

  }

  //取消上传
  CancelShow() {
    this.fileInfom = false;
  }

  ShowOK() {
    this.isOkLoadingfileInfom = true;
    this.fileInfom = false;
    this.isOkLoadingfileInfom = false;
  }

  //下载文件
  downLoadFile(data) {
    console.log(data)
    this.fileName = data.file_path.substring(9);
    // this.link = this.axios.domainTest1 + this.workName + '/' + this.fileName;
    this.link = this.axios.domainTest1 + "/" + this.fileName
    console.log(this.fileName, this.link)
  }

  //删除文件
  showDelFile(data) {
    this.isFileVisible = true;
    console.log(data)
    this.id = data.id;
  }

  //取消删除
  handleFileCancel() {
    this.isFileVisible = false;
  }

  //确认删除
  delFileOk() {
    this.isFileOkLoading = true;
    this.isFileVisible = false;
    this.isFileOkLoading = false;
    this.axios.axiosPost('DeleteWorkFile', { 'id': this.id })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          let listData = this.fileList.filter(res => res['id'] !== this.id)
          this.fileList = listData;
        }
      })
  }

  //退回工件
  return(item) {
    if (!item.timestamp) {
      this.id = item.id;
      this.unionorder = item.union_order;
      this.workerName = item.ljmc;
      // this.RemarkValue = item.remark;
      console.log(item, this.workerName)
      this.addOtherRemark = true;
      let index = item.remark.indexOf(this.storage.getStorageData('user').name)
      if (index === 0 && item['remark']) {
        this.RemarkValue = item.remark + '\n\n';
      } else {
        this.RemarkValue = this.storage.getStorageData('user').name + ' : \n\n' + item.remark;
      }
    } else {
      alert("該工件未停止計時")
    }
  }

  //取消备注
  CancelRemark() {
    this.addOtherRemark = false;
  }

  //添加其他备注（退回）
  RemarkOk() {

    if (this.RemarkValue.length != 0) {
      this.isOkLoadingOthRemark = true;
      this.addOtherRemark = false;
      this.isOkLoadingOthRemark = false;
      let content = '';
      content = this.RemarkValue;//姓名+内容
      console.log(content)
      this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "stage", "newValue1": 2, "stageValue": 1 }).then((data) => {
        console.log(data, "工单状态修改成功了,增加了编程的状态")
      })
      this.axios.axiosPost('UpdateWorkOrder', {
        'unionorder': this.unionorder, 'workorder': this.workerName, id: this.id,
        'remark': content, 'status': 2
      })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.unionorder, "type": 1, "status": 3 }).then((data) => {
              console.log("111111111111")
              console.log(data)
              if (!data["order"] || data["order"].length <= 0) {
                this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "stage", "newValue1": 2, "stageValue": 1, "newValue12": 3, "stageValue2": 0 }).then((data) => {
                  console.log(data, "工单状态修改成功了,取消了当前工单状态")
                })
              }
            })
            this.allUnion();
          }
        })
        .catch((err) => {
          console.log(err);
        })


    } else {
      alert("請輸入退單備註")
    }
  }

  //送出单选框
  selectCNC(value) {
    this.sendChoose = value;
    console.log("======" + this.sendChoose + "======")
  }

  //送出按钮
  send(item) {
    if (!item.timestamp) {
      console.log(item)
      this.isSendVisible = true;
      this.unionorder = item.union_order;
      this.workerName = item.ljmc;
      this.id = item.id;
      this.sjsj = item.songjian_shijian;
      this.jgjg = item.gjjcjg;
    } else {
      alert("該工件未停止計時")

    }

  }

  //取消送出
  handleSendCancel() {
    this.isSendVisible = false;
  }

  //确认送出
  sendOk() {
    this.isSendOkLoading = true;
    this.isSendVisible = false;
    this.isSendOkLoading = false;
    if (this.sjsj && this.sjsj != "") {
      if (this.jgjg) {
        if (this.sendChoose === 'OK') {
          this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "stage", "newValue1": 4, "stageValue": 1 }).then((data) => {
            console.log(data, "工单状态修改成功了,增加了编程的状态")
          })
          this.axios.axiosPost('UpdateWorkOrder', {
            'unionorder': this.unionorder, 'workorder': this.workerName, id: this.id, 'status': 4, "machine_end_date_2": ""
          })
            .then((data) => {
              console.log(data)
              if (data['result'] === 'ok') {
                // window.location.href = this.url;
                this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.unionorder, "type": 1, "status": 3 }).then((data) => {
                  console.log(data)
                  console.log(!data["order"])
                  console.log(data["order"].length)
                  if (!data["order"] || data["order"].length <= 0) {
                    this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.unionorder, "name1": "stage", "newValue1": 3, "stageValue": 0, "newValue12": 4, "stageValue2": 1 }).then((data) => {
                      console.log(data, "工单状态修改成功了,取消了当前工单状态")
                    })
                  }
                  this.allUnion();
                })
              }
            })
            .catch((err) => {
              console.log(err);
            })
        } else if (this.sendChoose === 'NG') {
          console.log("11111")
        }
      } else {
        alert("未填寫檢測結果")
      }
    } else {
      alert("未填寫送檢時間")
    }

  }

  //导出表格
  Export() {
    const exportItem = this.listOfData;
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(exportItem);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    var date = new Date();
    this.saveAsExcelFile(excelBuffer, date.toLocaleDateString() + '_' + 'report');
  }

  private saveAsExcelFile(buffer: any, fileName: string) {
    const data: Blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
    });
    FileSaver.saveAs(data, fileName + '.xlsx');
  }
  downLoad2(infom) {
    console.log(infom)
    this.fileInfom2 = true;
    this.link = this.axios.domainTest1;
    console.log(this.link)

    if (infom.imagefile) {
      this.imglist = infom.imagefile.split(",")
    } else {
      this.imglist = [];
    }
  }
  CancelShow2() {
    this.fileInfom2 = false;
  }
  ShowOK2() {
    this.fileInfom2 = false;
  }

}



